package com.localsocial.phonescreen;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.util.Log;
import oauth.signpost.OAuth;
import oauth.signpost.OAuthConsumer;
import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer;

public class LinkedInAPICall {
	
	private final String TAG = getClass().getName();
	private SharedPreferences prefs;
	private Context context;
	
	public LinkedInAPICall(Context context) {
		//this.prefs = prefs;
		this.context = context;
	}
	
	public String execute(String api_req) {
		String jsonOutput = "";
		
		try {
			jsonOutput = doGet(api_req,getConsumer());
			//Log.i(TAG, "json output:" + jsonOutput);
		} catch (Exception e) {
			Log.e(TAG, "Error executing request",e);
		}
		
		return jsonOutput;
	}
	
	private OAuthConsumer getConsumer() {
		prefs = PreferenceManager.getDefaultSharedPreferences(context);
		
		String token = this.prefs.getString(OAuth.OAUTH_TOKEN, "");
		String secret = this.prefs.getString(OAuth.OAUTH_TOKEN_SECRET, "");
		OAuthConsumer consumer = new CommonsHttpOAuthConsumer(Constants.LINKEDIN_KEY, Constants.LINKEDIN_SECRET);
		consumer.setTokenWithSecret(token, secret);
		return consumer;
	}
	
	private String doGet(String url,OAuthConsumer consumer) throws Exception {
		DefaultHttpClient httpclient = new DefaultHttpClient();
		HttpGet request = new HttpGet(url);
		// add header to return json instead of xml
		request.addHeader("x-li-format", "json");
		Log.i(TAG,"Requesting URL : " + url);
		consumer.sign(request);
		HttpResponse response = httpclient.execute(request);
		Log.i(TAG,"Statusline : " + response.getStatusLine());
		InputStream data = response.getEntity().getContent();
		BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(data));
		String responeLine;
		StringBuilder responseBuilder = new StringBuilder();
		while ((responeLine = bufferedReader.readLine()) != null) {
			responseBuilder.append(responeLine);
		}
		Log.i(TAG,"Response : " + responseBuilder.toString());
		return responseBuilder.toString();
	}
	
}

